<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of base_obj
 *
 * @author Juraj
 */
class base_obj {

    //put your code here

    public function getAllObjects($path) {
        $result = array();
        $folder = dir($path);
        while ($f = $folder->read()) {
            if ($f == "." || $f == ".." || $f == ".svn" || $f == 'base_obj.php')
                continue;
            $result[] = $f;
        }
        return $result;
    }

    public function getModule($id) {
        $id = (int) $id;

        if (empty($id) || ($id < 1)) {
            $error = new error_obj('bad layout id: ' . $id, get_class(), __FUNCTION__);
            return false;
        }

        $db_obj = new db_obj();
        if (!isset($GLOBALS['page']) || empty($GLOBALS['page'])) {
            $input = $GLOBALS['input'];
            $input = $this->goodInput($input);
            if ($input === false) {
                header("Location: " . ROOT . "zla adresa");
                exit;
            } else {
                $page = $db_obj->getOne("SELECT id FROM pages WHERE LOWER(title)='" . $input . "'");
                if ($page === null) {
                    header("Location: " . ROOT . "");
                    exit;
                }
                $GLOBALS['page'] = $page;
            }
        }
        $module = $db_obj->getRow("SELECT * FROM modules WHERE page_id='" . $GLOBALS['page'] . "' AND layout_id='" . $id . "' AND area_rights='0' AND group_rights='0' AND user_rights='0'");
        if ($_SESSION['user']['user_id'] != 0 || $_SESSION['user']['user_type_id'] != 0 || $_SESSION['user']['user_area_id'] != 0) {
            if ($_SESSION['user']['user_area_id'] != 0) {
                $area_module = $db_obj->getRow("SELECT * FROM modules WHERE area_rights='" . $_SESSION['user']['user_area_id'] . "' AND page_id='" . $GLOBALS['page'] . "' AND layout_id='" . $id . "'");
                if (!empty($area_module))
                    $module = $area_module;
            }
            if ($_SESSION['user']['user_type_id'] != 0) {
                $group_module = $db_obj->getRow("SELECT * FROM modules WHERE group_rights='" . $_SESSION['user']['user_type_id'] . "' AND page_id='" . $GLOBALS['page'] . "' AND layout_id='" . $id . "'");
                if (!empty($group_module))
                    $module = $group_module;
            }
            if ($_SESSION['user']['user_id'] != 0) {
                $user_module = $db_obj->getRow("SELECT * FROM modules WHERE user_rights='" . $_SESSION['user']['user_id'] . "' AND page_id='" . $GLOBALS['page'] . "' AND layout_id='" . $id . "'");
                if (!empty($user_module))
                    $module = $user_module;
            }
        }
        if (!empty($module)) {
            $MODULE = PATH_TO_MODULES . $module['module'] . '.php';
            $GLOBALS['module'] = $module['module'];
            if (trim($module['viewer'] == ''))
                $VIEWER = $module['module'];
            else
                $VIEWER = $module['viewer'];

            $GLOBALS['template_data'] = array();
            include($MODULE);
            $template = explode('/', $VIEWER);
            $pathToTemplate = '';
            for ($i = 0; $i < count($template) - 1; $i++) {
                $pathToTemplate .= $template[$i] . '/';
            }
            $template = $template[count($template) - 1] . '.tpl';

            if (file_exists(PATH_TO_TEMPLATES . $pathToTemplate . $template)) {
                $GLOBALS['template_data']['root'] = ROOT;
                $GLOBALS['template_data']['errors_alert'] = $GLOBALS['errors_alert'];
                $GLOBALS['template_data']['goods_alert'] = $GLOBALS['goods_alert'];
                $GLOBALS['template_data']['pathToError'] = PATH_TO_TEMPLATES . 'error_alert.tpl';
                $GLOBALS['template_data']['absPath'] = FILE;
                $GLOBALS['smarty']->template_dir = PATH_TO_TEMPLATES . $pathToTemplate;
                $GLOBALS['smarty']->assign("data", $GLOBALS['template_data']);
                $GLOBALS['smarty']->display($template);
                $this->debug("Template data $MODULE", $GLOBALS['template_data']);
            } else {
                $this->debug("Neexistujuci tpl", $pathToTemplate . $template . ' => neexistuje');
            }
        }
    }

    private function goodInput($input) {
        $input = trim($input);
        if (empty($input))
            return false;
        if ($input[0] == '-' || $input[0] == '_')
            return false;
        if (strlen($input) > 255)
            return false;
        $input = strip_tags($input);
        $input = htmlspecialchars($input);
        $input = $this->toLower($input);
        return $input;
    }

    public function toLower($input) {
        $input = str_replace('A', 'a', $input);
        $input = str_replace('Á', 'á', $input);
        $input = str_replace('B', 'b', $input);
        $input = str_replace('C', 'c', $input);
        $input = str_replace('Č', 'č', $input);
        $input = str_replace('D', 'd', $input);
        $input = str_replace('Ď', 'ď', $input);
        $input = str_replace('E', 'e', $input);
        $input = str_replace('É', 'é', $input);
        $input = str_replace('F', 'f', $input);
        $input = str_replace('G', 'g', $input);
        $input = str_replace('H', 'h', $input);
        $input = str_replace('I', 'i', $input);
        $input = str_replace('Í', 'í', $input);
        $input = str_replace('J', 'j', $input);
        $input = str_replace('K', 'k', $input);
        $input = str_replace('L', 'l', $input);
        $input = str_replace('Ľ', 'ľ', $input);
        $input = str_replace('Ĺ', 'ĺ', $input);
        $input = str_replace('M', 'm', $input);
        $input = str_replace('N', 'n', $input);
        $input = str_replace('Ň', 'ň', $input);
        $input = str_replace('O', 'o', $input);
        $input = str_replace('Ó', 'ó', $input);
        $input = str_replace('P', 'p', $input);
        $input = str_replace('Q', 'q', $input);
        $input = str_replace('R', 'r', $input);
        $input = str_replace('Ŕ', 'ŕ', $input);
        $input = str_replace('S', 's', $input);
        $input = str_replace('Š', 'š', $input);
        $input = str_replace('T', 't', $input);
        $input = str_replace('Ť', 'ť', $input);
        $input = str_replace('U', 'u', $input);
        $input = str_replace('Ú', 'ú', $input);
        $input = str_replace('V', 'v', $input);
        $input = str_replace('X', 'x', $input);
        $input = str_replace('Y', 'y', $input);
        $input = str_replace('Ý', 'ý', $input);
        $input = str_replace('Z', 'z', $input);
        $input = str_replace('Ž', 'ž', $input);
        return $input;
    }

    public function filterDiacritics($input, $extend = null) {
        $input = str_replace('á', 'a', $input);
        $input = str_replace('é', 'e', $input);
        $input = str_replace('í', 'i', $input);
        $input = str_replace('ó', 'o', $input);
        $input = str_replace('ô', 'o', $input);
        $input = str_replace('ú', 'u', $input);
        $input = str_replace('ď', 'd', $input);
        $input = str_replace('ť', 't', $input);
        $input = str_replace('ň', 'n', $input);
        $input = str_replace('ľ', 'l', $input);
        $input = str_replace('ĺ', 'l', $input);
        $input = str_replace('ŕ', 'r', $input);
        $input = str_replace('č', 'c', $input);
        $input = str_replace('š', 's', $input);
        $input = str_replace('ž', 'z', $input);
        $input = str_replace('ý', 'y', $input);
        $input = str_replace('ä', 'a', $input);
        $input = str_replace('Á', 'A', $input);
        $input = str_replace('É', 'E', $input);
        $input = str_replace('Í', 'I', $input);
        $input = str_replace('Ó', 'O', $input);
        $input = str_replace('Ú', 'U', $input);
        $input = str_replace('Ď', 'D', $input);
        $input = str_replace('Ť', 'T', $input);
        $input = str_replace('Ň', 'N', $input);
        $input = str_replace('Ľ', 'L', $input);
        $input = str_replace('Ĺ', 'L', $input);
        $input = str_replace('Ŕ', 'R', $input);
        $input = str_replace('Č', 'C', $input);
        $input = str_replace('Š', 'S', $input);
        $input = str_replace('Ž', 'Z', $input);
        $input = str_replace('Ý', 'Y', $input);

        if ($extend != null) {
            foreach ($extend as $e) {
                $input = str_replace($e['search'], $e['replace'], $input);
            }
        }

        return $input;
    }

    public function generateRandomString($n, $onlyNumeric = false, $onlyChar = false) {
        if ($onlyNumeric)
            $set = '0123456789';
        elseif ($onlyChar)
            $set = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        else
            $set = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $result = '';
        $interval = strlen($set) - 1;
        for ($i = 0; $i < $n; $i++) {
            $result .= $set[mt_rand(0, $interval)];
        }
        return $result;
    }

    public function debug($description, $value) {
        if (!isset($GLOBALS['debugs']))
            $GLOBALS['debugs'] = array();
        $GLOBALS['debugs'][] = array('description' => $description, 'value' => $value);
    }

    public function showDebug() {
        $GLOBALS['smarty']->template_dir = PATH_TO_TEMPLATES;
        $GLOBALS['smarty']->assign("error_data", $GLOBALS['errors']);
        $GLOBALS['smarty']->assign("debug_data", $GLOBALS['debugs']);
        $GLOBALS['smarty']->display('debugger.tpl');
    }

    public function smarty() {
        require(PATH_TO_SMARTY . "Smarty.class.php");
        $GLOBALS['smarty'] = new Smarty;
        foreach ($GLOBALS['smarty_functions'] as $name => $implementation) {
            $GLOBALS['smarty']->registerPlugin("function", $name, $implementation);
        }
    }

    public function convertDateTo($date, $output = 'date', $format = 'dd/mm/yyyy') {
        $date = trim($date);
        switch ($format) {
            case 'dd/mm/yyyy':
                $d = explode('/', $date);
                switch ($output) {
                    case 'date':
                        return $d[2] . '-' . $d[1] . '-' . $d[0];
                        break;
                    case 'dd/mm/yyyy':
                        return $d[0] . '/' . $d[1] . '/' . $d[2];
                        break;
                }
                break;
            case 'date':
                $d = explode('-', $date);
                switch ($output) {
                    case 'date':
                        return $d[0] . '-' . $d[1] . '-' . $d[2];
                        break;
                    case 'dd/mm/yyyy':
                        return $d[2] . '/' . $d[1] . '/' . $d[0];
                        break;
                    case 'dd.mm.yyyy':
                        return $d[2] . '.' . $d[1] . '.' . $d[0];
                        break;
                    case 'U':
                        return mktime(12, 0, 0, $d[1], $d[2], $d[0]);
                        break;
                }
                break;
            case 'datetime':
                $date = explode(' ', $date);
                $d = explode('-', $date[0]);
                switch ($output) {
                    case 'dd/mm/yyyy H:i:s':
                        return $d[2] . '/' . $d[1] . '/' . $d[0] . ' ' . $date[1];
                        break;
                    case 'U':
                        $t = explode(":", $date[1]);
                        return mktime($t[0], $t[1], $t[2], $d[1], $d[2], $d[0]);
                        break;
                }
                break;
        }
    }

    public function redirect($url) {
        if (isset($_SESSION['debug_mode']) && ($_SESSION['debug_mode'])) {
            self::debug("redirect to", '<a href="' . $url . '">' . $url . '</a>');
        } else {
            header("Location: " . $url);
            exit;
        }
    }

    public static function getMonthName($month, $lang = 'sk') {
        $months = array(
            'sk' => array(
                1 => 'Január',
                2 => 'Február',
                3 => 'Marec',
                4 => 'Apríl',
                5 => 'Máj',
                6 => 'Jún',
                7 => 'Júl',
                8 => 'August',
                9 => 'September',
                10 => 'Október',
                11 => 'November',
                12 => 'December',
            )
        );

        return $months[$lang][$month];
    }

    public static function my_nl2br($str) {
        $order = array("\r\n", "\n", "\r");
        $replace = '<br />';
        return str_replace($order, $replace, $str);
    }

    public static function security($levels) {
        $rights = 0;
        foreach ($levels as $level) {
            switch ($level) {
                case 'public':
                    if (isset($_SESSION['user']))
                        $rights ++;
                    break;
                case 'technic':
                    if (isset($_SESSION['user']) && !empty($_SESSION['user']['user_type_id']) && ($_SESSION['user']['user_type_id'] == USER_TYPE_TECHNIC))
                        $rights ++;
                    break;
                case 'client':
                    if (isset($_SESSION['user']) && !empty($_SESSION['user']['user_type_id']) && ($_SESSION['user']['user_type_id'] == USER_TYPE_CLIENT))
                        $rights ++;
                    break;
                case 'admin':
                    if (isset($_SESSION['user']) && !empty($_SESSION['user']['user_type_id']) && ($_SESSION['user']['user_type_id'] == USER_TYPE_ADMIN))
                        $rights ++;
                    break;
            }
        }

        if ($rights > 0)
            return true;

        return false;
    }

    public static function pretty_var_dump($variable, $level = 0, $key = "") {
        if ($level == 0) {
            $mt = "20px";
        } else {
            $mt = "0px";
        }
        echo '<div style="margin-top: ' . $mt . '">';
        if (is_array($variable)) {
            for ($i = 0; $i < $level; $i++) {
                echo ".&nbsp;&nbsp;&nbsp;&nbsp;";
            }
            if (!empty($key))
                echo "[$key] => ";
            echo "<i>" . gettype($variable) . "</i> (" . count($variable) . "){<br/>";
            $level += 1;
            foreach ($variable as $k => $value) {
                self::pretty_var_dump($value, $level, $k);
            }
            for ($i = 0; $i < $level - 1; $i++) {
                echo ".&nbsp;&nbsp;&nbsp;&nbsp;";
            }
            echo "}";
        } else {
            for ($i = 0; $i < $level; $i++) {
                echo ".&nbsp;&nbsp;&nbsp;&nbsp;";
            }
            if (!empty($key))
                echo "[$key] => ";
            echo "<i>" . gettype($variable) . "</i>: " . $variable . "<br/>";
        }
        echo "</div>";
    }

}

?>
